#include "./num_led.h"
#include "../compat.h"
#include "./i2c.h"
#include "../utils/delay.h"
#include "../rtx/rtx_os.h"

GPIO_INFO(TOP_SCK, GPIOB, 15)
GPIO_INFO(TOP_DAT, GPIOB, 14)

GPIO_INFO(BOTTOM_SCK, GPIOB, 12)
GPIO_INFO(BOTTOM_DAT, GPIOB, 13)

I2C_INFO(TOP, TOP_SCK, TOP_DAT, 10)
I2C_INFO(BOTTOM, BOTTOM_SCK, BOTTOM_DAT, 10)

#define A  0x01
#define B  0x02
#define C  0x04
#define D  0x08
#define E  0x10
#define F  0x20
#define G  0x40

const uint8_t NumList[] = {
    A + B + C + D + E + F,
    B + C,
    A + B + G + E + D,
    A + B + G + C + D,
    F + G + B + C,
    A + F + G + C + D,
    A + F + G + C + D + E,
    A + B + C,
    A + B + C + D + E + F + G,
    A + B + G + F + C + D,
};

void num_led_init() {
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;

    TOP_SCK_init(MODE_PP);
    TOP_DAT_init(MODE_PP);
    BOTTOM_SCK_init(MODE_PP);
    BOTTOM_DAT_init(MODE_PP);

    TOP_i2c_stop();
    BOTTOM_i2c_stop();
}


void num_led_top_show(uint16_t value) {

    uint8_t b3 = NumList[value / 1000];
    uint8_t b2 = NumList[(value / 100) % 10];
    uint8_t b1 = NumList[(value / 10) % 10];
    uint8_t b0 = NumList[value % 10];

    TOP_write(0x6800 | b3);
    TOP_write(0x6A00 | b2);
    TOP_write(0x6C00 | b1);
    TOP_write(0x6E00 | b0);
    TOP_write(0x4800 | 0x01);
}

void num_led_bottom_show(uint16_t value) {

    uint8_t b3 = NumList[value / 1000];
    uint8_t b2 = NumList[(value / 100) % 10];
    uint8_t b1 = NumList[(value / 10) % 10];
    uint8_t b0 = NumList[value % 10];

    BOTTOM_write(0x6800 | b3);
    BOTTOM_write(0x6A00 | b2);
    BOTTOM_write(0x6C00 | b1);
    BOTTOM_write(0x6E00 | b0);
    BOTTOM_write(0x4800 | 0x01);
}

